package com.ruoyi.framework.config;

import com.ruoyi.common.utils.JsonUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Redis使用JackJson序列化
 *
 * @author hcx
 */
public class JackJsonJsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    private final Class<T> clazz;

    public JackJsonJsonRedisSerializer(Class<T> clazz){
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null)
        {
            return new byte[0];
        }
        return JsonUtils.ClassAutoload.toJson(t).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return JsonUtils.ClassAutoload.formJson(str,clazz);
    }
}
